package com.jkhan.demo.threads.communication;

/**
 * @ClassName Product
 * @Description producer and customer
 * @Author hjk
 * @Date 2022/1/9 22:10
 **/
public class Product {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Producer producer = new Producer(clerk);
        Customer customer = new Customer(clerk);

        Thread producer1 = new Thread(producer);
        producer1.setName("生产者1");
        Thread producer2 = new Thread(producer);
        producer2.setName("生产者2");

        Thread customer1 = new Thread(customer);
        customer1.setName("消费者1");
        Thread customer2 = new Thread(customer);
        customer2.setName("消费者2");

        producer1.start();
        producer2.start();
        customer1.start();
        customer2.start();
    }

}

class Clerk {
    private int productNumber = 0;

    public synchronized void produceProduct() {
        if (productNumber < 20) {
            productNumber++;
            System.out.println(Thread.currentThread().getName() + ": 开始生产第" + productNumber + "个产品");

            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void consumeProduct() {
        if (productNumber > 0) {
            System.out.println(Thread.currentThread().getName() + ": 开始消费第" + productNumber + "个产品");
            productNumber--;

            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Producer implements Runnable {
    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ": 开始生产");

        while (true) {
            try {
                Thread.currentThread().sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.produceProduct();
        }
    }
}

class Customer implements Runnable {
    private Clerk clerk;

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ": 开始消费");

        while (true) {

            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.consumeProduct();
        }
    }
}

